<template>
    <div class="app-container">
        <el-row type="flex" class="row-bg btn-row" justify="end">
            <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('1007')" @click="exportData" type="primary" icon="el-icon-plus">{{$t('colTransaction.download')}}</el-button>
        </el-row>
        <el-collapse>
            <el-collapse-item>
                <div slot="title">
                    &nbsp;&nbsp;&nbsp;{{$t('colTransaction.click_filter')}}&nbsp;&nbsp;&nbsp;<i class="icon iconfont icon-filter" style="font-size: 10px"></i>
                </div>
                <el-form :inline="true" :model="q" class="demo-form-inline query" label-position="left" >
                    <el-row >
                        <div class="col-container">
                            <span class="searchlabel">{{$t('colTransaction.bankcard_name')}}</span>
                        </div>
                        <div class="input-container-left">
                            <el-input v-model="bankcard_name" :placeholder="$t('colTransaction.bankcard_name')" prefix-icon="el-icon-edit"></el-input>
                        </div>
                        <div class="col-container">
                            <span class="searchlabel">{{$t('colTransaction.bank')}}</span>
                        </div>
                        <div class="input-container-left">
                            <el-input v-model="q.bank" :placeholder="$t('colTransaction.bank')" prefix-icon="el-icon-edit"></el-input>
                        </div>
                    </el-row>
                    <br>
                    <el-row >
                        <div class="col-container">
                            <span class="searchlabel">{{$t('colTransaction.amount')}}</span>
                        </div>
                        <div class="input-container-left">
                            <el-input v-model="q.amount" :placeholder="$t('colTransaction.amount')" prefix-icon="el-icon-edit"></el-input>
                        </div>
                        <div class="col-container">
                            <span class="searchlabel">{{$t('colTransaction.balance')}}</span>
                        </div>
                        <div class="input-container-left">
                            <el-input v-model="q.balance" :placeholder="$t('colTransaction.balance')" prefix-icon="el-icon-edit"></el-input>
                        </div>
                        <div class="col-container">
                            <span class="searchlabel">{{$t('colTransaction.merchant')}}</span>
                        </div>
                        <div class="input-container-left">
                            <el-select v-model="q.mch_id" :placeholder="$t('colTransaction.merchant')" prefix-icon="el-icon-edit">
                                <el-option :label="$t('colTransaction.all')" value=""></el-option>
                                <el-option v-for="(item, key) of MchList" :key="key" :label="item.name" :value="parseInt(item.id)"></el-option>
                            </el-select>
                        </div>
                    </el-row>
                    <br>
                    <el-row>
                        <div class="col-container">
                            <span class="searchlabel">{{$t('colTransaction.transaction_time')}}</span>
                        </div>
                        <el-form-item>
                            <el-date-picker v-model="q.transaction_time.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('order.select_datetime')"></el-date-picker>
                            -<el-date-picker v-model="q.transaction_time.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('order.select_datetime')"></el-date-picker>
                        </el-form-item>
                        <div style="float:right; margin-right:330px;">
                            <el-button type="primary" @click="query">{{$t('colTransaction.search')}}</el-button>
                            <el-button type="danger" @click="reload">{{$t('colTransaction.reset')}}</el-button>
                        </div>
                    </el-row>
                </el-form>
            </el-collapse-item>
        </el-collapse>
        <el-row>
            <div class="col-container" style="margin-left: 5px">
                <span class="searchlabel">{{$t('pmTransaction.total_income')}}</span>
            </div>
            <div class="input-container-left">
                <span style="color: #f00;line-height: 80px; font-weight:600">{{this.totalDeposit}}</span>{{$t('pmTransaction.currency')}}
            </div>
            <div class="col-container" style="margin-left:-40px">
          <span class="searchlabel">
          {{$t('pmTransaction.total_expenses')}}
          </span>
            </div>
            <div class="input-container-left">
                <span style="color: #f00;line-height: 80px; font-weight:600">{{this.totalExpenses}}</span>{{$t('pmTransaction.currency')}}
            </div>
        </el-row>
        <el-table :data="listData.list" v-loading.body="listLoading" @sort-change="sortlist" element-loading-text="Loading" stripe border fit highlight-current-row>
            <el-table-column prop="bankcard_name" :label="$t('colTransaction.bankcard_name')" sortable align="center"></el-table-column>
            <!--<el-table-column prop="type" :label="$t('colTransaction.type')" align="center">-->
                <!--<template slot-scope="scope">{{ getTypew(scope.row.type)}}</template>-->
            <!--</el-table-column>-->
            <el-table-column prop="mch_id" :label="$t('colTransaction.mch_id')" sortable align="center"></el-table-column>
            <el-table-column prop="bank" :label="$t('colTransaction.bank')" sortable align="center"></el-table-column>
            <el-table-column prop="amount" :label="$t('colTransaction.amount')" sortable align="center">
                <template slot-scope="scope">
                    {{scope.row.amount?scope.row.amount.toFixed(2):0.00}}
                </template>
            </el-table-column>
            <el-table-column prop="pay_amount" :label="$t('colTransaction.pay_amount')" sortable align="center">
                <template slot-scope="scope">
                    {{scope.row.pay_amount?scope.row.pay_amount.toFixed(2):0.00}}
                </template>
            </el-table-column>
            <el-table-column prop="withdraw_amount" :label="$t('colTransaction.withdraw_amount')" sortable align="center">
                <template slot-scope="scope">
                    {{scope.row.withdraw_amount?scope.row.withdraw_amount.toFixed(2):0.00}}
                </template>
            </el-table-column>
            <el-table-column prop="balance" :label="$t('colTransaction.balance')" sortable align="center"></el-table-column>
        </el-table>
    </div>
</template>

<script>
    import { getBankRecordList, getMchList } from '@/api/merchant'
    import {queryFilter} from '@/utils/patch'
    import timedate from '@/utils/timedate.js'
    import i18n from '@/lang/index';
    import { json2excel } from 'js2excel';
    import { jsonKeyToTitleCase } from '@/utils/index'

    export default {
        data() {
            return {
                listData: {},
                notes: {},
                q: {transaction_time: {$gte: timedate.dateYesterday, $lt: timedate.dateToday}, $size: 9999999999},
                MchList: [],
                listLoading: true,
                id: null,
                amount: null,
                pay_amount: null,
                withdraw_amount: null,
                totalExpenses: 0.00,
                totalDeposit: 0.00,
                transfer_from: {$like: ''},
                bankcard_name: null,
                types: {
                    0: 'Deposit',
                    1: 'Withdrawal'
                },
                matchItems: {
                    0: 'Unmatched',
                    1: 'Matched'
                }
            }
        },
        created() {
            this.getList()
            this.getMchList()
        },
        deactivated(){
            this.listLoading = false
        },
        methods: {
            query(){
                this.q.$size = 9999999999;
                this.getList()
            },
            exportData() {
                this.getList(true)
            },
            reload() {
                this.bankcard_name = ''
                this.notes = {};
                this.q = {transaction_time: {$gte: timedate.dateYesterday, $lt: timedate.dateToday}, $size: 9999999999}
                this.getList()
            },
            sortlist(sort){
                this.q.$orderby = sort.prop
                this.getList()
            },
            getTypew(id){
                if(id != null) {
                    var trans = 'pmTransaction.types.' + id.toString();
                    return i18n.t(trans);
                } else {
                    return '';
                }
            },
            getList(isDownload = false) {
                if(this.bankcard_name !== null){
                    this.q.bankcard_name = this.bankcard_name ? {$like: this.bankcard_name} : ''
                }
                if(this.notes.$like){
                    this.q.notes = this.notes
                }
                let params = Object.assign({
                    $orderby: '-transaction_time',
                    card_type: this.$store.state.app.BankCardType.WITHDRAW,
                    is_stats: 1
                }, this.q)

                if(isDownload){
                    params['$size'] = 9999999999
                }

                let queryObj = queryFilter(params)
                this.listLoading = true
                getBankRecordList(queryObj).then(res => {
                    if (res.status === 0) {
                        if(isDownload){
                            this.download(res.data.list);
                        } else {
                            this.listLoading = false
                            this.listData = res.data
                            this.totalDeposit = this.listData.income ? parseFloat(this.listData.income).toFixed(2) : 0.00;
                            this.totalExpenses = this.listData.spend ? parseFloat(this.listData.spend).toFixed(2) : 0.00;
                        }
                    }
                })
            },
            getMchList(){
                getMchList({$size: -1}).then(res => {
                    if (res.status === 0) {
                        this.MchList = res.data.list
                    }
                })
            },
            paresAcctDetail(detail){
                let arr = [];
                if(detail.indexOf('(')) {
                    arr = detail.split('(')
                }
                return arr;
            },
            download(data) {
                this.listLoading = false
                let transactions = [...data]
                let downloadData = transactions.map(item => ({
                    card_code: item.bankcard_name,
                    type: this.getTypew(item.type),
                    company: item.mch_id,
                    bank: item.bank,
                    amount: item.amount ? item.amount.toFixed(2) : 0.00,
                    pay_amount: item.pay_amount ? item.pay_amount.toFixed(2) : 0.00,
                    withdraw_amount: item.withdraw_amount ? item.withdraw_amount.toFixed(2) : 0.00,
                    transaction_balance: item.balance,
                    transaction_time: item.transaction_time
                }));
                var exportData = jsonKeyToTitleCase(downloadData)
                json2excel({ data: exportData, name: 'Transactions', formateDate: 'yyyy/mm/dd' })
            }
        }
    }

    export const enTransactionCol = {
        click_filter: 'Click to filter',
        transaction_time: 'Transaction time',
        select_datetime: 'Select date and time',
        creation_datetime: 'Created Time',
        merchant: 'Company',
        choose: 'Please Choose',
        matching_status: 'Matching Status',
        all: 'All',
        bankcard: 'Bankcard',
        bankcard_name: 'Card Code',
        bankcard_number: 'Bank card no.',
        bank: 'Bank',
        amount: 'Amount',
        pay_amount: 'Pay Amount',
        withdraw_amount: 'Withdraw Amount',
        match_orderid: 'Match order ID',
        search: 'Search',
        reset: 'Reset',
        remarks: 'Remarks',
        updated_at: 'Update time',
        status: 'Matching mode',
        balance: 'Transaction Balance',
        transfer_to: 'Transfer to',
        transfer_from: 'Transfer from',
        types: {
            0: 'Deposit',
            1: 'Withdrawal'
        },
        type: 'Type',
        mch_id: 'Company',
        payee: 'Payee',
        total_revenue: 'Total Revenue',
        currency: 'RMB',
        action: 'Action',
        manual_match: 'manual match',
        orderdetail: 'Order Detail',
        download: 'Download'
    }

    export const zhTransactionCol = {
        click_filter: '点击筛选',
        transaction_time: '银行到账时间',
        select_datetime: '选择日期时间',
        creation_datetime: '我方到账时间',
        merchant: '公司',
        choose: '请选择',
        matching_status: '匹配状态',
        all: '所有',
        bankcard: '银行卡',
        bankcard_name: '银行卡名称',
        bankcard_number: '银行卡号',
        bank: '银行',
        amount: '金额',
        pay_amount: '收入金额',
        withdraw_amount: '支出金额',
        match_orderid: '匹配订单ID',
        search: '查询',
        reset: '重置',
        remarks: '备注',
        updated_at: '创建时间',
        status: '匹配方式',
        balance: '余额',
        transfer_to: '收款方',
        transfer_from: '付款方',
        types: {
            0: '存款',
            1: '取款'
        },
        payee: '收款人',
        total_revenue: '总收入',
        currency: '元',
        type: '交易类型',
        mch_id: '公司',
        detail: '订单详情',
        manual_match: '手动匹配',
        orderdetail: '订单详情',
        download: '导出数据'
    }
</script>
